package com.sh.cloudrender.domian.service.kube;

import com.sh.cloudrender.infrastructure.configuration.KubeConfiguration;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1Namespace;
import io.kubernetes.client.openapi.models.V1NamespaceList;
import io.kubernetes.client.openapi.models.V1ObjectMeta;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class NamespaceService {

    @Autowired
    private CoreV1Api coreV1Api;
    @Autowired
    private KubeConfiguration kubeConfiguration;

    /**
     * 创建kubernetes namespace
     *
     * @param namespace
     * @return
     */
    public V1Namespace createNamespace(String namespace) {
        V1Namespace v1Namespace = new V1Namespace();
        v1Namespace.setApiVersion("v1");
        v1Namespace.setKind("Namespace");
        V1ObjectMeta metaData = new V1ObjectMeta();
        metaData.setNamespace(namespace);
        metaData.setName(namespace);
        v1Namespace.setMetadata(metaData);
        V1Namespace resp = null;
        try {
            resp = coreV1Api.createNamespace(v1Namespace, null, null, null, null);
        } catch (ApiException e) {
            log.error("create namespace:{} failed, msg:{}", namespace, e.getResponseBody());
            return null;
        }

        return resp;
    }

    /**
     * 获取kubernetes对应的namespace
     *
     * @param namespace
     * @return
     */
    public V1Namespace getNamespace(String namespace) {
        V1Namespace v1Namespace = null;
        try {
//            ApiClient apiClient = kubeConfiguration.apiClient();
//            // 禁用 SSL 验证
//            apiClient.setVerifyingSsl(false);
//            CoreV1Api api = new CoreV1Api(apiClient);
            V1NamespaceList namespaceList = coreV1Api.listNamespace(null,null,null,null,null,null,null,null,null,null);

            // 输出命名空间列表
            List<V1Namespace> items = namespaceList.getItems();
            for (V1Namespace v1NamespaceItem : items) {
                System.out.println("Namespace: " + v1NamespaceItem.getMetadata().getName());
            }
            v1Namespace = coreV1Api.readNamespace(namespace, null);
        } catch (ApiException e) {
            System.err.println("Exception when calling CoreV1Api#listNamespace");
            e.printStackTrace();
        }

        return v1Namespace;
    }

    public void initNamespace(String namespace) throws RuntimeException {
        V1Namespace v1Namespace = getNamespace(namespace);
        if (v1Namespace == null) {
            v1Namespace = createNamespace(namespace);
            if (v1Namespace == null) {
                throw new RuntimeException("init engine container namespace error");
            }
        }
    }
}
